package implementation1.app.commands;

import exceptions.CommandErrorFromUserException;
import exceptions.CommandException;
import implementation1.data.states.TerminatedStatus;
import interfaces.app.IProcess;
import interfaces.data.IHandle;

import java.util.Collection;

/**
 * Class for creating process which kill concrete process.
 * Created: 27.11.11
 *
 * @author Jan Svab
 */
public class Kill extends Command
{
    /**
     * Default constructor.
     *
     * @param parent parent process over which is command processed
     * @param handle parameters of command
     */
    public Kill(IProcess parent, IHandle handle)
    {
        super(parent, handle);
    }

    /**
     * Main code of the command.
     *
     * @param args arguments of command
     * @throws exceptions.CommandException Thrown if occurs an error during processing of the command.
     */
    @Override
    public void mainCommand(String[] args) throws CommandException
    {
        if (args == null || args.length != 1)
        {
            throw new CommandErrorFromUserException(bundle.getString("error.arguments.wrongCount"));
        }

        int pid = Integer.parseInt(args[0]);

        Collection<IProcess> processes = getRootProcess().getChildrenRecursively();

        for (IProcess process : processes)
        {
            if (Thread.interrupted()) //in other process was created request on terminate this process
            {
                status = new TerminatedStatus();
                break;
            }

            if (hasEndStatus()) //thread should quit
            {
                break;
            }

            if (process.getPid() == pid)
            {
                process.terminate();
                return;
            }
        }

        throw new CommandErrorFromUserException(bundle.getString("error.kill.wrongPid"));
    }
}
